package com.ccsoft.gsms.security;

import com.ccsoft.gsms.model.SysPermission;
import com.ccsoft.gsms.model.SysUser;
import com.ccsoft.gsms.model.UserFuse;
import com.ccsoft.gsms.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:MyUserDetailsService
 * @Description:TODO
 * @Author:chanchaw
 * @Date:2019-11-25 16:11
 * @Version:1.0
 **/
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.selectByUserId(username);// 查询获取用户信息
        if( sysUser==null ){
            System.out.println("没有查询到 userid = " + username);
            return null;
        }

        // 方法 selectPermissionsByUserId 要自己手动写 - 不是 Mybatis-Generator 生成的
        // 获取指定用户拥有的所有权限，权限类 SysPermission 要求实现 SpringSecurity5 的GrantedAuthority
        List<SysPermission> list = sysUserService.selectPermissionsByUserId(username);

        // 实现了接口 UserDetails 的用户类
        // 下面要做两步：
        // 1. 将原始用户类对象赋值给该融合类
        // 2. 给该融合类中的权限赋值
        UserFuse user = new UserFuse();
        user.setSysUser(sysUser);

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for(SysPermission item:list){
            authorities.add(new SimpleGrantedAuthority(item.getPermissionid()));
        }
        user.setAuthorities(authorities);

        System.out.println("loadUserByUsername数据解析：");
        System.out.println("userid = " + sysUser.getUserid());
        System.out.println("password = " + sysUser.getPassword());
        System.out.println("权限是：" + list.toString());
        return user;
    }
}
